package site.marqstree.latte.core.delegates.web;

import android.os.Bundle;
import android.webkit.WebView;

import androidx.annotation.Nullable;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

import site.marqstree.latte.core.app.ConfigKeys;
import site.marqstree.latte.core.app.Latte;
import site.marqstree.latte.core.delegates.LatteDelegate;
import site.marqstree.latte.core.delegates.web.route.RouteKeys;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.core.delegates.web
 * 文件名: WebDelegate
 * 创建者: marqstree
 * 创建时间: 2020/1/31 11:48
 * 描述: TODO
 */
public abstract class WebDelegate extends LatteDelegate {
    private WebView mWebView = null;
    private final ReferenceQueue<WebView> WEB_VIEW_QUEUE = new ReferenceQueue<>();
    private String mUrl = null;
    private boolean mIsWebViewAvailable = false;
    private LatteDelegate mTopDelegate = null;

    public WebDelegate() {
    }

    public abstract IWebViewInitializer setInitializer();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        mUrl = args.getString(RouteKeys.URL.name());
        //初始化配置WebView
        setupWebView();
    }

    private void setupWebView(){
        if (mWebView != null) {
            mWebView.removeAllViews();
            mWebView.destroy();
        }

        //创建WevView初始化器
        final IWebViewInitializer initializer = setInitializer();
        if(initializer==null)
        {
            throw new NullPointerException("Initializer of WebView is null!");
        }else{
            //采用代码方式创建WebView，而不是在布局文件中静态定义
            //优点：在布局文件中静态声明，会导致内存泄漏
            //创建弱引用WebView
            // 保证在垃圾回收时，一定被清除
            final WeakReference<WebView> webViewWeakReference =
                    new WeakReference<>(new WebView(getContext()), WEB_VIEW_QUEUE);
            //从弱引用中获取WevView
            mWebView = webViewWeakReference.get();
            //初始化WebView配置
            initializer.initWebView(mWebView);
            //给WebView配置WevViewClient
            //设置路由，采用原生Fragment代替web跳转
            mWebView.setWebViewClient(initializer.getWebViewClient());
            //给WebView配置WevChromeClient
            //WebView加载WebChromeClient,才能支持alert弹框
            mWebView.setWebChromeClient(initializer.getWebChromeClient());
            //获取js接口对象名
            final String name = Latte.getConfiguration(ConfigKeys.JAVASCRIPT_INTERFACE);
            //给WebView注册Js接口对象，该对象被挂载在window对象下
            mWebView.addJavascriptInterface(LatteWebInterface.create(this), name);
            mIsWebViewAvailable = true;
        }
    }

    public WebView getWebView() {
        if (mWebView == null) {
            throw new NullPointerException("WebView IS NULL!");
        }
        //若初始化还未完成，返回null
        return mIsWebViewAvailable ? mWebView : null;
    }

    public String getUrl() {
        if (mUrl == null) {
            throw new NullPointerException("WebView IS NULL!");
        }
        return mUrl;
    }

    public void setTopDelegate(LatteDelegate delegate) {
        mTopDelegate = delegate;
    }

    public LatteDelegate getTopDelegate() {
        if (mTopDelegate == null) {
            mTopDelegate = this;
        }
        return mTopDelegate;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mWebView != null) {
            mWebView.onResume();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mIsWebViewAvailable = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.removeAllViews();
            mWebView.destroy();
            mWebView = null;
        }
    }
}
